package com.example.f8399.testdemo.service;

import android.app.IntentService;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.annotation.Nullable;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;

import java.text.SimpleDateFormat;

/**
 * Created by f8399 on 2018/9/3.
 */

public class StepCounterService extends IntentService {

    private SensorManager mSensorManager;
    private SensorEventListener mListener;
    private Sensor mSensorCounter;
    private boolean mHasSensor;

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     */
    public StepCounterService() {
        super("StepCounterService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        //判断支不支持计步
        mHasSensor = getPackageManager().hasSystemFeature(PackageManager.FEATURE_SENSOR_STEP_COUNTER);
        if (mHasSensor) {
            mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
            mSensorCounter = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);

            mListener = new SensorEventListener() {
                @Override
                public void onSensorChanged(SensorEvent event) {
                    float value = event.values[0];
                    LogUtils.d("时间：" + TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")) + "-->" + value + "步");
                }

                @Override
                public void onAccuracyChanged(Sensor sensor, int accuracy) {

                }
            };


        }else {
            ToastUtils.showShort("该设备不支持计步功能");
        }

        if (mHasSensor) {
            mSensorManager.registerListener(mListener, mSensorCounter, SensorManager.SENSOR_DELAY_FASTEST);
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mHasSensor) {

            mSensorManager.unregisterListener(mListener,mSensorCounter);
            LogUtils.d("计步关闭");
        }
    }
}
